package cn.lyjuan.aliyun.mq.conf.java.dynamic;


import cn.lyjuan.aliyun.mq.conf.java.conf.MQUserCst;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * 资源配置属性类
 * Created by chad on 2016/10/10.
 */
public class MQUserCstDynamicImpl extends ADynamicBean
{
    public static final String NAME_SUFFIX = "Cst";

    /**
     * 环境变量
     */
    private String proFilePath;


    public MQUserCstDynamicImpl(String baseName, String proFilePath)
    {
        super(baseName, NAME_SUFFIX);
        this.proFilePath = proFilePath;
    }

    @Override
    public void register(DefaultListableBeanFactory beanFactory)
    {
        if (isContainsBean(beanFactory)) return;// 已包含

        Properties pro = null;

        try
        {
            Resource res = new FileSystemResource(proFilePath);
            pro = PropertiesLoaderUtils.loadProperties(res);
        } catch (IOException e)
        {
            throw new RuntimeException(e);
        }

        // 将属性加载到BeanDefinition中
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MQUserCst.class);
        builder.getBeanDefinition().setAttribute("id", this.getQuiteBeanName());
        builder.addConstructorArgValue(pro);

        // 将Bean注册到SpringBeanFactory中
        beanFactory.registerBeanDefinition(this.getQuiteBeanName(), builder.getBeanDefinition());
    }
}
